<?php

namespace App\Dao;

use App\Model\AnchorVideo;
use App\Model\Topic;
use App\Model\TopicTag;
use App\Model\TopicZan;
use App\Utils\AliyunOssHelper;
use App\Utils\FunUtil;
use App\Utils\MemcacheClient;
use Hyperf\Context\ApplicationContext;

class TopicDao
{
    private static $instance;

    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = Applicationcontext::getcontainer()->get(self::class);
        }
        return self::$instance;
    }

    /**
     * 通过条件获取动态列表
     * @param $uid
     * @param $where
     * @param $page
     * @param $pageSize
     * @param $version_code
     * @return mixed
     */
    public function getConditionTopicList($uid, $where, $page, $pageSize, $version_code)
    {
        // $data = $this->topicModel->getList($where, $page, $pageSize);
        $data = $this->getList($where, $page, $pageSize);
        $tags = TopicTag::getAllTopicTagsCache();

        if (empty($data)) return [];
        $zanModel = new TopicZan();
        foreach ($data as &$v) {
            $v['is_new_user'] = 0;
            if ($v['register_time'] + 7 * 86400 >= time()) {
                $v['is_new_user'] = 1;
            }

            $v['zan_count'] = $zanModel->zanCount($v['id'], 1);
            $v['head_image'] = FunUtil::formatHeadImg($v['head_image']);
            $v['auth'] = [
                // 'real_card_status' => $v['is_cardAuth'] == 1 ? 1 : 0,
                // 'real_img_status' => in_array($v['is_faceAuth'], [1, 3]) ? 1 : 0,
                'real_education_status' => 0,
                'is_binding_phone' => $v['is_binding']
            ];

            if ($v['super_noble'] == 1) {
                $v['noble'] = 0;
            }

            if ($v['photo']) {
                $v['photo'] = explode(',', $v['photo']);
                foreach ($v['photo'] as &$p) {
                    if ($version_code >= 128) {
                        // 版本号大于
                        $p = AliyunOssHelper::compressImageHandle($p, 1000);
                    }
                }
            }
            $v['reply_count'] = (int)$v['reply_count'];
            $v['status'] = (int)$v['status'];
            $v['time'] = (int)$v['time'];
            $v['is_zan'] = $zanModel->isZan($uid, $v['id'], 1);

            if ($v['tags']) {
                $v['tags'] = array_map(function ($value) use ($tags) {
                    return $tags[$value] ?? [];
                }, explode(',', $v['tags']));
            } else {
                $v['tags'] = [];
            }
        }
        return $data;
    }

    /**
     * Note - h获取动态原始数据列表
     * DateTime 2024/7/22 11:40
     * User Admin
     * @param $where
     * @param $page
     * @param $pageSize
     * @return mixed[]
     */
    public function getList($where, $page, $pageSize)
    {
        $start = ($page - 1) * $pageSize;
        $limit = ' LIMIT ' . $start . ',' . $pageSize;

        // $sql = "SELECT t.*, u.`nickname`,u.`head_image`,u.sex,u.register_time,u.age,u.level,f.accept_video,u.is_cardAuth,u.is_faceAuth,f.accept_audio,f.video_price,f.audio_price,f.real_name,u.vip,u.noble,u.super_noble,u.is_disturb,u.head_image_status,u.is_binding FROM `".$this->table."` t inner join `".$this->tableUser."` u ON t.uid = u.id left join `".$this->tableAnchor."` f ON t.uid = f.uid WHERE is_show=0 and (f.status = 0 or isnull(f.status)) and ".$where.$order.$limit;

        // $users = DB::table($this->table . ' AS t')
        $data = Topic::query()->from('tb_topic AS topic')
            ->join('tb_user AS u', 'topic.uid', '=', 'u.id')
            ->leftJoin('tb_anchor AS anchor', 'topic.uid', '=', 'anchor.uid')
            ->select([
                    'topic.*',
                    'u.nickname',
                    'u.head_image',
                    'u.sex',
                    'u.register_time',
                    'u.age',
                    'u.level',
                    'u.vip',
                    'u.noble',
                    'u.super_noble',
                    'u.is_disturb',
                    'u.head_image_status',
                    'u.is_binding',
                    'anchor.accept_audio',
                    'anchor.accept_video',
                    'anchor.video_price',
                    'anchor.audio_price',
                    'anchor.real_name']
            )
            ->where('topic.is_show', 0)
            ->where(function ($query) {
                $query->whereNull('anchor.status')->orWhere('anchor.status', 0);
            })
            ->where($where)
            ->orderBy('topic.publish_time', 'DESC')
            ->orderBy('topic.time', 'DESC')
            ->skip($start)
            ->take($pageSize) // 或者使用 ->limit($limit)
            ->get();
        return $data->toArray();
    }

    /**
     * 获取当前帖子信息
     * @param $id
     * @return mixed
     */
    public function getTopicInfo($id)
    {
        $data = Topic::query()->from('tb_topic AS topic')
            ->join('tb_user AS u', 'topic.uid', '=', 'u.id')
            ->leftJoin('tb_anchor AS anchor', 'topic.uid', '=', 'anchor.uid')
            ->select([
                'topic.*',
                'u.nickname',
                'u.head_image',
                'u.sex',
                'u.age',
                'u.level',
                'u.vip',
                'u.noble',
                'u.super_noble',
                'u.is_disturb',
                'u.head_image_status',
                'u.is_binding',
                'anchor.accept_audio',
                'anchor.accept_video',
                'anchor.video_price',
                'anchor.audio_price',
                'anchor.real_name'])
            ->where('topic.id', $id)
            ->first();
        return modelToArray($data);
    }


    /**
     * Note - 获取动态/视频 回复、点赞未读消息数
     * DateTime 2024/8/15 11:57
     * User Admin
     * @param $uid
     * @return mixed
     */
    public function notReadNum($uid)
    {
        // $sql="select count(a.id) as count from tb_topic a left join tb_topic_reply r on a.id=r.t_id where a.uid={$uid} and a.status=1 and r.status=0 and is_read=0";
        // $pd = $this->createCommand($sql);
        // $pd->execute([]);
        // $result = $pd->fetch(PDO::FETCH_ASSOC);
        // $num=$result['count'];
        // 回帖
        $replyNum = Topic::query()->leftJoin('tb_topic_reply', 'tb_topic.id', '=', 'tb_topic_reply.t_id')
            ->where('tb_topic.uid', $uid)
            ->where('tb_topic.status', 1)
            ->where('tb_topic_reply.status', 0)
            ->where('tb_topic_reply.is_read', 0)
            ->count();
        // 点赞
        // $sql="select count(a.id) as count from tb_topic a left join tb_topic_zan z on a.id=z.tr_id where a.uid={$uid} and a.status=1 and z.type=1 and is_read=0";
        // $pd = $this->createCommand($sql);
        // $pd->execute([]);
        // $result = $pd->fetch(PDO::FETCH_ASSOC);
        // $num+=$result['count'];
        $zanNum = Topic::query()->leftJoin('tb_topic_zan', 'tb_topic.id', '=', 'tb_topic_zan.tr_id')
            ->where('tb_topic.uid', $uid)
            ->where('tb_topic.status', 1)
            ->where('tb_topic_zan.type', 1)
            ->where('tb_topic_zan.is_read', 0)
            ->count();

        // $sql="select count(a.id) as count from tb_anchor_video a left join tb_anchor_video_zan z on a.id=z.video_id where a.anchor_id={$uid} and a.status=1 and z.is_read=0";
        // $pd = $this->createCommand($sql);
        // $pd->execute([]);
        // $result = $pd->fetch(PDO::FETCH_ASSOC);
        // $num+=$result['count'];
        // 视频点赞
        $videoZanNum = AnchorVideo::query()->leftJoin('tb_anchor_video_zan', 'tb_anchor_video.id', '=', 'tb_anchor_video_zan.video_id')
            ->where('tb_anchor_video.anchor_id', $uid)
            ->where('tb_anchor_video.status', 1)
            ->where('tb_anchor_video_zan.is_read', 0)
            ->count();

        return $replyNum + $zanNum + $videoZanNum;
    }


}